<?php
require_once '/virtual/twotiger/lib/GoogleClientApi/Google_Client.php';
require_once '/virtual/twotiger/lib/GoogleClientApi/contrib/Google_YouTubeService.php';
require_once ("/virtual/twotiger/lib/library/SecureManager.class.php");
//require_once 'Zend/Loader.php';
//$frontController = Zend_Controller_Front::getInstance();
//$appConfig = $frontController->getParam('bootstrap')->getOptions();
$secureManager = new SecureManager();
$client = new Google_Client();
$client->setDeveloperKey("AIzaSyAXsMaLR1ELiBTit2XqmrYfMS3pb7XLiOo"); // API key
$youtube = new Google_YoutubeService($client);

$keyword = "cat sleeping";
$get_order= 'rating';

if(isset($_GET['keyword'])){
 $keyword =$secureManager->sanitize($_GET['keyword']);
}
if(isset($_GET['order'])){
 $get_order =$secureManager->sanitize($_GET['order']);
}

$maxResults = "50";

    $type = "video";
    //relevance、published、viewCount、rating
    //$get_order= 'viewCount';
    //$safeSearch='strict';
   // $videoCategoryId =10;i
try {


    $ytRes1st = $youtube->search->listSearch('id,snippet', array(
        'q' => $keyword,
        'maxResults' => $maxResults,
        'order' => '$get_order',
        'type' => $type,
      //  'publishedAfter' => $publishedAfter,
      //  'publishedBefore' => $publishedBefore,
    //    'videoCategoryId' => 10,
    //    'pageToken' => $get_pageToken,
        'order' => $get_order,
    //    'safeSearch' => $safeSearch,
    ));

    if ($ytRes1st) {
        
        //var_export($ytRes1st);
        $ytRes1st_kind = $ytRes1st['kind'];
        $ytRes1st_etag = $ytRes1st['etag'];
        $ytRes1st_totalResults = $ytRes1st['pageInfo']['totalResults'];
        $ytRes1st_resultsPerPage = $ytRes1st['pageInfo']['resultsPerPage'];
        $ytRes1st_nextPageToken = $ytRes1st['nextPageToken'];
//        $ytRes1st_prevPageToken = $ytRes1st['prevPageToken'];

        $movies = '';
        $channelIds = '';
        $videoIds = '';
        $results = array();

        foreach ($ytRes1st['items'] as $item) {
            $movieTitle = $item['snippet']['title'];
            $channelId = $item['snippet']['channelId'];
            $channelTitle = $item['snippet']['channelTitle'];
            $publishedAt = $item['snippet']['publishedAt'];
            $videoId = $item['id']['videoId'];
            $videoIds .= $item['id']['videoId'] . ",";          // 動画再生回数、like・dislikeの取得用
            $moviePath = '/v';
// 検索結果は一旦配列に保存する（ループが多くなるので極力APIリクエストを減らす）
            $results[] = array('movieTitle' => $movieTitle,
                'channelId' => $channelId,
                'publishedAt' => $publishedAt,
                'videoId' => $videoId,
            );
        }
    }

// 動画再生回数、like・dislikeの取得
// APIリクエスト用のビデオID（複数）最後のカンマを削除
    $videoIds = rtrim($videoIds, ",");
// APIリクエスト
    $ytRes2nd = $youtube->videos->listVideos($videoIds, 'snippet,statistics,contentDetails', array());
    $i = 0;
    
  
// APIレスポンス
    if ($ytRes2nd) {
        foreach ($ytRes2nd['items'] as $item) {
            //var_export($item);
            $ytRes2nd_channelId = $item['snippet']['channelId'];                    // チャンネルID
            $thumbnail = $item['snippet']['thumbnails']['default']['url']; // サムネイル
             // var_export($item['snippet']['thumbnails']['default']);
            $duration = $item['contentDetails']['duration'];              // 動画時間
            $viewCount = $item['statistics']['viewCount'];                 // 再生数
            $likeCount = $item['statistics']['likeCount'];                 // 高評価数
            $dislikeCount = $item['statistics']['dislikeCount'];    
            // 低評価数
// 配列の最後に追加する
            $results[$i] += array("thumbnail" => $thumbnail,
                "duration" => $duration,
                "viewCount" => $viewCount,
                "likeCount" => $likeCount,
                "dislikeCount" => $dislikeCount,
                "videoId" =>$videoId,
            );
            $i = $i + 1;
        }
    }

    $htmlBody = "<ol data-role='listview' data-inset='true'>\n";
//var_export($results);
    foreach ((array)$results as $key => $value) {
        $htmlBody .= <<<END
<li>
<a href="http://www.youtube.com/watch?v={$value['videoId']}" >
<img src="{$value['thumbnail']}" /> 
{$value["movieTitle"]}<br />
ViewCount:{$value["viewCount"]}<br />
LikeCount:{$value["likeCount"]}<br />
<!--videoId:{$value["videoId"]}<br />-->
</a>
</li>\n
END;
    }

    $htmlBody .= "</ol>\n";
} catch (Google_ServiceException $e) {
    $htmlBody .= sprintf('<p>A service error occurred: <code>%s</code></p>', htmlspecialchars($e->getMessage()));
} catch (Google_Exception $e) {
    $htmlBody .= sprintf('<p>An client error occurred: <code>%s</code></p>', htmlspecialchars($e->getMessage()));
}
?>
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="keywords" content="World cats sleeping">
<meta name="description" content="<?php echo $keyword ?>">
<meta name="author" content="ken kodama">
<meta name="msvalidate.01" content="B17F46571AEB8DF77AAD776AA1A4EE23" />
 <meta name="viewport" content="width=device-width, initial-scale=1">
<title>World Cats Sleeping </title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.0/jquery.mobile-1.4.0.min.css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.0/jquery.mobile-1.4.0.min.js"></script>
 <link rel="stylesheet" href="/css/blocks_it_style.css" media="screen" />
<style type="text/css">
      #header {
          
      }
      #content{
          /*margin-top: 50px; */
          
      }
      .my_adslot { width: 320px; height: 50px; }
      @media(min-width: 500px) { .my_adslot { width: 468px; height: 60px; } }
      @media(min-width: 800px) { .my_adslot { width: 728px; height: 90px; } }
</style>
 </head>
 <body>
<div data-role="page">
	<div id="header" data-role="header" data-position="fixed" >
  <!--      <h3>Ranking(rating)</h3> -->
        <div class="ad">
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- WorldMenDancing -->
<ins class="adsbygoogle my_adslot"
     style="display:inline-block"
     data-ad-client="ca-pub-4498051423313001"
     data-ad-slot="2530811460"
     data-ad-format="auto"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div></div>
	<div id="content" rdata-role="content" >
            <?php
            echo $htmlBody;
            ?>     
        </div>
	<div data-role="footer" ></div>
</div>

  </body>
</html>
